import React, { Component } from 'react';
import {getMovies, getMoviesByGenre} from '../services/fakeMovieService';
import { genres, getGenres } from '../services/fakeGenreService';
import ListGroup from './list/listGroup';
import MoviesTable from './table/moviesTable';
import style from './movies.module.css'

class Movies extends Component {
    constructor() {
        super()
        this.state = {
            movies: [],
            genres: [],
            selectedGenre: "全部电影"
        }
    }

    componentDidMount() {
        this.setState({
            movies: getMovies(),
            genres: getGenres()
        })
    }

    handleGenreSelect = genres => {
        this.setState({
            selectedGenre: genres,
        })
    }

    handleGetData = () => {
        const { selectedGenre } = this.state
        const newMovies = selectedGenre !== "全部电影" ? getMoviesByGenre(selectedGenre) : getMovies()
        return { total: newMovies.length, movies: newMovies }
    }

    handleLike = movie => {
        const movies = [...this.state.movies]
        const index = movies.indexOf(movie)
        movies[index] = { ...movies[index] }
        movies[index].liked = !movies[index].liked
        this.setState({
            movies
        })
    }

    render() {
        const { genres, selectedGenre } = this.state
        const { total, movies } = this.handleGetData()
        return (
            <div className={`row  ${style.pt}`}>
                <div className='col-2'>
                    <ListGroup
                        items={genres}
                        selectedItem={selectedGenre}
                        onItemSelect={this.handleGenreSelect}
                    />
                </div>
                <div className='col'>
                    {total ? (
                        <>
                            <p>一共有{total}条相关电影</p>
                            <MoviesTable
                                movies={movies}
                                onLike={this.handleLike}
                            />
                        </>
                    ) : (
                        <p>没有相关电影</p>
                    )}

                </div>
            </div>
        );
    }
}

export default Movies;
